package org.devocean.groupbuying.dao.impl;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.devocean.groupbuying.dao.MenuLocalizationDAO;
import org.devocean.groupbuying.domain.Menu;
import org.devocean.groupbuying.domain.MenuLocalization;
import org.springframework.stereotype.Repository;

@Repository
public class MenuLocalizationDAOImpl implements MenuLocalizationDAO {

	@PersistenceContext
	private EntityManager em;
	public void linkToMenu(MenuLocalization menuLocalization) {
		for (Menu menu : menuLocalization.getMenus()) {
			menu.setMenuLocalization(menuLocalization);
		}
	}

	public MenuLocalization saveMenuLocalization(MenuLocalization menuLocalization) {
		linkToMenu(menuLocalization);
		em.persist(menuLocalization);
		em.flush();
		return menuLocalization;
	}

	public MenuLocalization updateMenuLocalization(
			MenuLocalization menuLocalization) {
		linkToMenu(menuLocalization);
		final MenuLocalization merged = em.merge(menuLocalization);
		em.flush();
		return merged;
	}

	public MenuLocalization findMenuById(Integer menuId) {
		final Query query = em
				.createQuery("select distinct ml from MenuLocalization ml LEFT JOIN FETCH ml.menus m where m.menuID=:menuId");
		query.setParameter("menuId", menuId);

		return (MenuLocalization) query.getResultList().get(0);
	}
	

	public MenuLocalization findMenuLocalizationById(Integer localizationKey) {
		
		final Query query = em
				.createQuery("select distinct ml from MenuLocalization ml LEFT JOIN FETCH ml.menus m where ml.menuLocalizationID=:localizationKey");
		query.setParameter("localizationKey", localizationKey);

		return (MenuLocalization) query.getResultList().get(0);
	}

	public void deleteMenuLocalization(Integer id) {
		final MenuLocalization localisationKey = em.find(MenuLocalization.class, id);
		em.remove(localisationKey);
	}

}
